{% load static %}
<html>
<head>
    <title>学生列表（含班级名称）</title>
    <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script>
    <style>
        /* 全局基础样式 */
        * {
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f8f9fa;
            padding: 20px;
        }

        /* 表格容器样式 */
        .table-container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        /* 表格主体样式 */
        .student-table {
            width: 100%;
            border-collapse: collapse;
            border-spacing: 0;
        }

        .student-table th {
            background-color: #2c3e50;
            color: white;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            position: relative;
            cursor: pointer;
            user-select: none;
        }

        .student-table th:hover {
            background-color: #34495e;
        }

        .student-table th.sortable::after {
            content: '↑↓';
            position: absolute;
            right: 10px;
            opacity: 0.6;
            font-size: 14px;
        }

        .student-table th.asc::after {
            content: '↑';
            color: #3498db;
        }

        .student-table th.desc::after {
            content: '↓';
            color: #3498db;
        }

        .student-table td {
            padding: 15px;
            border-bottom: 1px solid #eee;
            color: #333;
        }

        .student-table tr:hover {
            background-color: #f8f9fa;
            transition: background-color 0.2s ease;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .student-table {
                font-size: 14px;
            }

            .student-table th,
            .student-table td {
                padding: 10px;
            }

            .table-container {
                border-radius: 6px;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            }
        }

        /* 加载动画 */
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            color: #3498db;
            z-index: 1000;
        }

        /* 状态提示 */
        .status-message {
            padding: 15px;
            border-radius: 6px;
            margin: 20px 0;
            text-align: center;
        }

        .status-error {
            background-color: #ffebee;
            color: #b71c1c;
        }
    </style>
</head>
<body>
    <h1>学生列表</h1>
    <div class="table-container">
        <div id="statusMessage" class="status-message" style="display: none;"></div>
        <table id="studentTable" class="student-table">
            <thead>
                <tr>
                    <th class="sortable">ID</th>
                    <th class="sortable">姓名</th>
                    <th class="sortable">性别</th>
                    <th class="sortable">学号</th>
                    <th class="sortable">出生日期</th>
                    <th class="sortable">所属班级</th>
                </tr>
            </thead>
            <tbody>
                <!-- 动态数据将插入此处 -->
            </tbody>
        </table>
    </div>

    <script>
        $(document).ready(function() {
            const $tableBody = $("#studentTable tbody");
            const $statusMessage = $("#statusMessage");
            const $tableContainer = $(".table-container");
            let sortColumn = null;
            let sortOrder = 'asc';
            let originalData = []; // 存储原始数据用于排序

            // 显示状态提示
            function showStatus(message, isError = false) {
                $statusMessage.text(message)
                    .removeClass('status-error')
                    .toggleClass('status-error', isError)
                    .fadeIn(200)
                    .delay(3000)
                    .fadeOut(200);
            }

            // 显示加载动画
            function showLoading() {
                $tableContainer.prepend('<div class="loading-overlay">数据加载中...</div>');
            }

            // 隐藏加载动画
            function hideLoading() {
                $tableContainer.find('.loading-overlay').remove();
            }

            // 渲染表格数据
            function renderTable(data) {
                $tableBody.empty();
                data.forEach(student => {
                    const row = `
                        <tr>
                            <td>${student.id || '-'}</td>
                            <td>${student.name || '未填写'}</td>
                            <td>${student.gender === '男' ? '男' : student.gender === '女' ? '女' : '未知'}</td>
                            <td>${student.student_id || '-'}</td>
                            <td>${student.birth_date ? new Date(student.birth_date).toLocaleDateString() : '未填写'}</td>
                            <td>${student.grade?.name || '未分配'}</td>
                        </tr>
                    `;
                    $tableBody.append(row);
                });
            }

            // 获取学生数据
            function fetchStudentData() {
                showLoading();
                $.ajax({
                    url: "/students/",
                    method: "GET",
                    dataType: "json",
                    success: function(response) {
                        hideLoading();
                        if (response.code !== 200) {
                            showStatus(`获取数据失败：${response.message || '未知错误'}`, true);
                            return;
                        }
                        originalData = response.data; // 存储原始数据
                        renderTable(response.data);
                    },
                    error: function(xhr) {
                        hideLoading();
                        showStatus(`网络请求失败：${xhr.statusText}`, true);
                    }
                });
            }

            // 初始化加载数据
            fetchStudentData();

            // 表头排序功能
            $("#studentTable th.sortable").click(function() {
                const column = $(this).text().toLowerCase();
                if (sortColumn === column) {
                    sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
                } else {
                    sortColumn = column;
                    sortOrder = 'asc';
                }

                // 更新表头样式
                $("#studentTable th").removeClass('asc desc');
                $(this).addClass(sortOrder);

                // 排序数据（前端临时排序，实际项目建议后端排序）
                const sortedData = [...originalData].sort((a, b) => {
                    const valA = a[column] || '';
                    const valB = b[column] || '';

                    if (typeof valA === 'number' && typeof valB === 'number') {
                        return sortOrder === 'asc' ? valA - valB : valB - valA;
                    }
                    return sortOrder === 'asc' ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
                });

                renderTable(sortedData);
            });

            // 窗口大小变化时调整表格布局
            $(window).on('resize', function() {
                if ($(window).width() <= 768) {
                    $tableContainer.css('overflow-x', 'auto');
                } else {
                    $tableContainer.css('overflow-x', 'hidden');
                }
            }).trigger('resize');
        });
    </script>
</body>
</html>